package pers.cz.utils;

import org.luaj.vm2.LuaTable;
import org.slf4j.Logger;
import pers.cz.model.SystemPartitionRelation;
import org.luaj.vm2.LuaFunction;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.script.LuaScriptEngine;

import javax.script.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 分表规则容器，里面存放所有的分表规则以及lua脚本引擎
 * @program: PostGirl-panent
 * @description: PartitionContext
 * @author: Cheng Zhi
 * @create: 2022-04-20 20:45
 **/
public final class PartitionContext {

    public Map<String, PartitionConfig> context = new HashMap<String, PartitionConfig>();
    private static final String LUA_CALL_SCRIPT_FUNC_NAMW="partition_rule";
    private static final String LUA_CALL_SCRIPT_PARAM_NAME="table_partition_params";

    public void addConfig(
            int schemeId,
            String tableName,
            String script,
            Map<String, String> constParam,
            Map<String, SystemPartitionRelation> partitionRelationParam) throws ScriptException {

        PartitionConfig config=new PartitionConfig(tableName);
        LuaScriptEngine engine=new LuaScriptEngine();
        config.setScriptEngine(engine, script);
        context.put(tableName, config);
    }

    /**
     * 执行分表脚本
     * @param tableName
     * @param partitionParams
     * @param sqlOpType
     * @return
     */
    public String eval(String tableName,Map partitionParams,String sqlOpType) throws ScriptException {

        PartitionConfig config=context.get(tableName);
        if(config==null) {
            return null;
        }

        Bindings bind = new SimpleBindings();
        //Bindings bind = currentContext.getBindings(ScriptContext.ENGINE_SCOPE);
        //bind.putAll(config.getEngineBindings());
        bind.put(LUA_CALL_SCRIPT_PARAM_NAME, LuaScriptUtils.toLua(partitionParams));
        config.invokeRaw(bind);
        LuaFunction luafunc = (LuaFunction) bind.get(LUA_CALL_SCRIPT_FUNC_NAMW);
        LuaValue param = (LuaValue) bind.get(LUA_CALL_SCRIPT_PARAM_NAME);

        LuaValue result = luafunc.call(param);
        if(result.istable()){
            System.out.println("返回的是table");
        }else{
            throw new IllegalArgumentException("The lua script must return a lua Table");
        }

        return result.toString();
    }


}
